import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ycbl/common/EventBus.dart';
import 'package:ycbl/config/bl_constant.dart';
import 'package:ycbl/utils/PrefUtil.dart';
import 'package:ycbl/utils/log_util.dart';
import 'package:ycbl/view_model/SearchViewModel.dart';
import 'package:ycbl/widget/provider/bl_provider_widget.dart';
import 'package:ycbl/widget/refesh/bl_smart_refresher.dart';
import 'package:ycbl/widget/search/AutoComplete.dart';
import 'package:ycbl/widget/search/Suggestions.dart';
import 'package:ycbl/widget/search/search.dart';

import '../ProductItemCell.dart';

class BLSearchDelegate extends SearchBLDelegate<String> {
  StreamSubscription _searchSubscription;
  bool _hasDeleteIcon = true;
  @override
  String get searchFieldLabel => '请输入关键词';

  @override
  TextStyle get searchFieldStyle => new TextStyle(color: Color(0XFF333333),fontSize: 12);

  @override
  List<Widget> buildBLActions(BuildContext context) {
    // TODO: implement buildBLActions
//    throw UnimplementedError();
    return [
      GestureDetector(
          onTap: () {
            close(context, null);
          },
          child: Container(
              padding: EdgeInsets.fromLTRB(0.0, 0.0, 14.5, 0.0),
              alignment: Alignment.center,
              child: Text("取消",style: TextStyle(color: Color(0XFF666666),fontSize: 15),))),
    ];
  }

  @override
  Widget buildBLLeading(BuildContext context) {
    // TODO: implement buildBLLeading
    return Container(child: Text(""));
  }

  @override
  Widget buildBLResults(BuildContext context) {
    // 取消搜索侦听
    _searchSubscription.cancel();
    // 简单显示搜索结果，并未真正去请求网络，后面文章会继续讲解如何通过api查询
    return BLProviderWidget<SearchViewModel>(
      notifierModel: SearchViewModel(BLConstant.BASE_API_URL +
          "?s=Ycsc.Com.Lists&tableId=353&pageId=6407&source=1&PRODUCT_NAME_2_andOr=0&PRODUCT_NAME_strCond_pld=0&PRODUCT_NAME_strVal_pld=$query"),
      onModelReady: (model) {
        LogUtil.e('onModelReady....');
        model.initData();
      },
      consumerBuilder: (context, searchModel, child) {
        return searchModel.simpleStateWidget(
          contentWidget: BLSmartRefresher(
            controller: searchModel.refreshController,
            onRefresh: () {
              LogUtil.d('onRefresh....');
              searchModel.refresh();
            },
            enablePullUp: true,
            onLoading: () {
              LogUtil.d('onLoadMore....');
              searchModel.loadMore();
            },
            child: ListView.builder(
              itemBuilder: (context, index) {
                LogUtil.d('itemBuilder.... $index');
                return ProductItemCell(
                  productCourse: searchModel.list[index].productCourse,
                  productName: searchModel.list[index].productName,
                  startDate: searchModel.list[index].startDate,
                  endDate: searchModel.list[index].endDate,
                  rnNumber: searchModel.list[index].rnNumber,
                  teacherHead: searchModel.list[index].teacherHead,
                  teacherName: searchModel.list[index].teacherName,
                  nowNumber: searchModel.list[index].nowNumber,
                  userIds:  searchModel.list[index].userIds,
                  productNowPrice: searchModel.list[index].productNowPrice,
                  productOldPrice: searchModel.list[index].productOldPrice,
                  allItemData: searchModel.list[index].allItemData,
                );
              },
              itemCount: searchModel?.list?.length ?? 0,
            ),
          ),
        );
      },
    );
  }

  @override
  Widget buildBLSuggestions(BuildContext context) {
    // 事件侦听
    _searchSubscription = eventBus.on<SearchEvent>().listen((event) {
      this.popResults(context);
      this.setSearchKeyword(event.keywords);
      //历史中增加搜索记录
      List<String> nowList = PrefUtil.getStringList("search_history_Keywords");
      LogUtil.e("nowList.length-1 ${nowList.toString()}");
      LogUtil.e("nowList.length0 ${event.keywords}");
      if(nowList!=null){//如果搜过，放到列表的第一位置
        if(nowList.contains(event.keywords)){
          nowList.remove(event.keywords);
          LogUtil.e("nowList.length1 ${event.keywords}");
          nowList.add(event.keywords);
          LogUtil.e("nowList.length1 ${event.keywords}");
        }else{
          nowList.add(event.keywords);
          LogUtil.e("nowList.length2 ${nowList.length}");
        }

      }else{

        nowList=new List<String>();
        nowList.add(event.keywords);
        LogUtil.e("nowList.length3 ${nowList.length}");
      }
      PrefUtil.saveStringList("search_history_Keywords",nowList);
      List<String> nowList22 = PrefUtil.getStringList("search_history_Keywords");
      LogUtil.e("nowList.length4 ${nowList22.toString()}");
    });

    /// 将方法作为参数传递给子组件调用，展示使用非EventBus方式通信
    return query.isEmpty
        ? Suggestions()
        : AutoComplete(query, this.popResults, this.setSearchKeyword);
  }

  /// 设置query
  Future<void> setSearchKeyword(String searchKeyword) async {
    query = searchKeyword;
    if (query.isEmpty) {
      _hasDeleteIcon=false;
    } else {
      _hasDeleteIcon=true;
    }
  }

  /// 搜索结果展示
  void popResults(BuildContext context) {
    showBLResults(context);
  }

  @override
  Widget buildBLClear(BuildContext context) {
    LogUtil.e("buildBLClear");
    return  Padding(
        padding: EdgeInsetsDirectional.only(
            start: 2.0, end: _hasDeleteIcon ? 20.0 : 0),
        child: _hasDeleteIcon
            ? new InkWell(
            onTap: (() {
              query = "";
              showBLSuggestions(context);
              _hasDeleteIcon = false;
//              setState(() {
//                widget.controller.text = '';
//                _hasDeleteIcon = false;
//              });
            }),
            child: Icon(
              Icons.clear,
              size: 18.0,
              color: Colors.black,
            ))
            : new Text(''));
  }
}
